# -*- coding: utf-8 -*-

import torch.nn as nn
import torch
import math


class PositionalEmbedding(nn.Module):
    """位置嵌入"""

    def __init__(self, d_model, max_len=512):
        """

        :param d_model: 维度
        :param max_len: 句子最大长度
        """
        super().__init__()

        # 在日志空间中一次计算位置编码
        pe = torch.zeros(max_len, d_model).float()
        pe.require_grad = False

        position = torch.arange(0, max_len).float().unsqueeze(1)
        div_term = (torch.arange(0, d_model, 2).float() * -(math.log(10000.0) / d_model)).exp()

        pe[:, 0::2] = torch.sin(position * div_term)
        pe[:, 1::2] = torch.cos(position * div_term)

        pe = pe.unsqueeze(0)    # torch.Size([1, max_len, d_model])

        self.register_buffer('pe', pe)

    def forward(self, x):
        return self.pe[:, :x.size(1)]
